package testProxy.javassist;

import java.lang.reflect.Method;

import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import testProxy.DBQuery;
import testProxy.IDBQuery;

public class Javassist {
	/**
	 * Javassist库实现的动态代理
	 * 
	 * @return
	 */
	public static IDBQuery createJavassistProxy() {
		ProxyFactory factory = new ProxyFactory();
		factory.setInterfaces(new Class[] { IDBQuery.class });
		IDBQuery proxy = null;

		class ProxyMethodHandler implements MethodHandler {
			private IDBQuery proxied = null;

			public ProxyMethodHandler(IDBQuery proxied) {
				this.proxied = proxied;
			}

			@Override
			public Object invoke(Object arg0, Method method, Method arg2, Object[] arg3) throws Throwable {
				// System.out.println("Javassist Method Handler invoke.");
				return method.invoke(proxied, arg3);
			}
		}

		factory.setHandler(new ProxyMethodHandler(new DBQuery()));
		try {
			proxy = (IDBQuery) factory.create(null, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return proxy;
	}
}
